import asyncio
from utils import device
from lib.api import iot

port = 80
protocol = "http"


def create_handler():
    global protocol
    if protocol == "http":
        from lib.server.http import handler

        return handler.handle_client

    from lib.server.tcp import handler

    return handler.handle_client


def test_connection():
    from lib.config.index import (
        sensor_config,
        server_config,
        user_config,
        device_config,
        wifi_config,
    )

    global port, protocol

    ip = device.info["ifconfig"]["ip"]
    mask = device.info["ifconfig"]["mask"]
    gateway = device.info["ifconfig"]["gateway"]
    dns = device.info["ifconfig"]["dns"]
    device_id = device.get_id()
    data = f"{ip},{port},{protocol},{device_id},start"
    network_info = {
        "ip": ip,
        "mask": mask,
        "gateway": gateway,
        "dns": dns,
    }
    value = {
        "server_info": network_info,
        "device_info": device.get_info(),
        "server_config": server_config.get_config(),
        "user_config": user_config.get_config(),
        "device_config": device_config.get_config(),
        "sensor_config": sensor_config.get_config(),
        "wifi_config": wifi_config.get_config(),
    }
    try:
        iot.upload_server_log(data, value)
    except Exception as e:
        pass


def Main(server_protocol, server_port):
    global protocol, port

    protocol = server_protocol
    port = server_port

    ip = device.get_ip()

    if port == 80:
        print(f"{protocol} server started at http://{ip}")
    else:
        print(f"{protocol} server started at http://{ip}:{port}")
    return asyncio.start_server(create_handler(), "0.0.0.0", port)


if __name__ == "__main__":
    try:
        asyncio.run(Main("http", 80))
    finally:
        asyncio.new_event_loop()
